package com.goktech.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.goktech.pojo.Swiper;
import com.goktech.mapper.SwiperMapper;
import com.goktech.service.SwiperService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.goktech.utils.CacheClient;
import com.goktech.utils.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.goktech.utils.Constants.*;

/**
 * <p>
 * 轮播图 服务实现类
 * </p>
 *
 * @author 初茶
 * @since 2023-05-16
 */
@Service
public class SwiperServiceImpl extends ServiceImpl<SwiperMapper, Swiper> implements SwiperService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<List<Swiper>> allSwiper() {
        String redisCache = stringRedisTemplate.opsForValue().get(SWIPER_KEY);
        if (redisCache != null) {
            return Result.ok(JSONUtil.toList(redisCache, Swiper.class));
        }
        List<Swiper> swiperList = baseMapper.selectList(Wrappers.emptyWrapper());
        CacheClient cacheClient = new CacheClient(stringRedisTemplate);
        cacheClient.set(SWIPER_KEY, swiperList, SWIPER_TTL, TimeUnit.DAYS);
        return Result.ok(swiperList);
    }
}
